<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>拍照</title>
  </head>
  <body>
    <video id="videoRef"></video>
    <div>
      <button onclick="shoot()">拍摄</button>
      <div id="picWrapRef"></div>
    </div>
    <div>
      <button onclick="startRecord()">开启录制</button>
      <button onclick="stopRecord()">停止录制</button>
      <video id="recordRef"></video>
    </div>
    <script>
      const mediaDevices = window.navigator.mediaDevices

      var mediaRecorder = null

      async function checkCamera() {
        const device = await mediaDevices.enumerateDevices()
        console.log('device', device)
      }

      async function useCamera() {
        try {
          // 获取摄像头
          const stream = await mediaDevices.getUserMedia({
            audio: false,
            video: {
              width: 500,
              height: 500,
              // facingMode: { exact: 'environment' }, // 强制后置镜头
              // facingMode: 'user', // 强制前置镜头
            },
          })
          // 将数据流赋值给video的srcObject属性
          videoRef.srcObject = stream
          // 调取play方法播放
          videoRef.play()
          // 创建MediaReocrd对象，以便录制
          mediaRecorder = new MediaRecorder(stream)
          let chunks = []
          mediaRecorder.ondataavailable = function (e) {
            chunks.push(e.data)
          }
          mediaRecorder.onstop = function () {
            var blob = new Blob(chunks, { type: 'audio/ogg;codecs=opus' })
            recordRef.src = URL.createObjectURL(blob)
          }
        } catch (err) {
          console.log('err', err)
        }
      }

      // 拍照
      function shoot() {
        if (!videoRef) return
        const canvas = document.createElement('canvas')
        canvas.width = videoRef.clientWidth
        canvas.height = videoRef.clientHeight
        const ctx = canvas.getContext('2d')
        ctx.drawImage(videoRef, 0, 0, canvas.width, canvas.height)
        picWrapRef.appendChild(canvas)
      }

      function startRecord() {
        mediaRecorder.start()
      }

      function stopRecord() {
        mediaRecorder.stop()
      }

      window.onload = function () {
        useCamera()
      }
    </script>
  </body>
</html>